package com.music.mysongs.helper

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Rect
import android.net.Uri
import com.music.mysongs.utils.MyApplication.Companion.context
import java.io.ByteArrayOutputStream

class ImgHelper {
    fun getBitmapFromUri(uri: Uri) =
        context.contentResolver?.openFileDescriptor(uri, "r")?.use {
            BitmapFactory.decodeFileDescriptor(it.fileDescriptor)
        }

    fun generateScaledBmp(
        srcBmp: Bitmap,
        targetWidth: Int,
        targetHeight: Int,
        quality: Int
    ): Bitmap? {
        val result = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(result)
        val rect = Rect(0, 0, result.width, result.height)
        canvas.drawBitmap(srcBmp, null, rect, null)
        if (!srcBmp.isRecycled) {
            srcBmp.recycle()
        }
        result.compress(Bitmap.CompressFormat.JPEG, quality, ByteArrayOutputStream())
        return result
    }
}